from asyncio.events import get_event_loop, new_event_loop
from asyncio.tasks import sleep
from re import T
from fastapi import APIRouter, WebSocket,WebSocketDisconnect
from fastapi.responses import HTMLResponse
import asyncio
import threading
from guac.tunnel import GuacamoleTunnel
import websockets

guacStream=APIRouter()

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept(subprotocol="guacamole")
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)


manager = ConnectionManager()

@guacStream.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.send_personal_message(f"You wrote: {data}", websocket)
            #await manager.broadcast(f"Client #{client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        #await manager.broadcast(f"Client #{client_id} left the chat")

async def send2ws_client(ws_a: WebSocket,guac_tun):
    print('start   1')
    while True:
        data= guac_tun.receive()
        print("websocket A sent:", data)
        await ws_a.send_text(data)
        
async def run(websocket, tun):
    def _run1(websocket, tun):
        loop=new_event_loop()
        loop.run_until_complete(send2ws_client(websocket, tun))
    threading.Thread(target=_run1,args=(websocket, tun)).start()
    while True:
        data =await websocket.receive_text()
        print("websocket A received:", data)
        tun.send(data)

@guacStream.websocket("/guac/stream")
async def websocket_endpoint(websocket: WebSocket):
    tunnel=GuacamoleTunnel(host='161.189.186.160',port=4822,debug=False)
    await websocket.accept(subprotocol="guacamole")
    #await websocket.accept()
    tun=tunnel.create_tunnel(
    'ssh',
    remote_host='127.0.0.1',
    remote_port='22',
    remote_width='700',
    remote_height='500',
    remote_dpi='96',
    remote_username='root',
    remote_password='chaospig123.')
    await asyncio.create_task(run(websocket,tun))
    
    